WaterEditor.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using FlatKit.Water;
  6. using UnityEditor;
  7. using UnityEngine;
  8. using UnityEngine.Rendering;
  9. public class FlatKitWaterEditor : ShaderGUI {
  10. private Gradient _gradient;
  11. private const string RenderingOptionsName = "Rendering Options";
  12. private GUIStyle _foldoutStyle;
  13. private static readonly Dictionary<string, bool> FoldoutStates =
  14. new Dictionary<string, bool> { { RenderingOptionsName, false } };
  15. public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) {
  16. Material targetMaterial = materialEditor.target as Material;
  17. string[] keywords = targetMaterial.shaderKeywords;
  18. if (!targetMaterial.IsKeywordEnabled("_COLORMODE_LINEAR") &&
  19. !targetMaterial.IsKeywordEnabled("_COLORMODE_GRADIENT_TEXTURE")) {
  20. targetMaterial.EnableKeyword("_COLORMODE_LINEAR");
  21. }
  22. bool isColorModeGradient = targetMaterial.IsKeywordEnabled("_COLORMODE_GRADIENT_TEXTURE");
  23. int originalIntentLevel = EditorGUI.indentLevel;
  24. int foldoutRemainingItems = 0;
  25. bool latestFoldoutState = false;
  26. _foldoutStyle ??= new GUIStyle(EditorStyles.foldout) {
  27. fontStyle = FontStyle.Bold,
  28. margin = {
  29. left = -10
  30. },
  31. padding = {
  32. left = 20
  33. },
  34. };
  35. foreach (MaterialProperty property in properties) {
  36. bool skipProperty = false;
  37. if (isColorModeGradient) {
  38. skipProperty |= ShowColorGradientExportBox(materialEditor, property);
  39. }
  40. {
  41. var brackets = property.displayName.Split('[', ']');
  42. foreach (var bracket in brackets) {
  43. if (bracket.Contains("FOLDOUT") || !property.displayName.Contains('[' + bracket + ']')) {
  44. continue;
  45. }
  46. bool isNegative = bracket.StartsWith("!");
  47. bool isPositive = !isNegative;
  48. var param = bracket.TrimStart('!');
  49. bool keywordOn = Array.IndexOf(keywords, param) != -1;
  50. if (isPositive && !keywordOn) {
  51. skipProperty = true;
  52. }
  53. if (isNegative && keywordOn) {
  54. skipProperty = true;
  55. }
  56. if (skipProperty) {
  57. break;
  58. }
  59. }
  60. }
  61. // Foldouts.
  62. {
  63. string displayName = property.displayName;
  64. if (displayName.Contains("FOLDOUT")) {
  65. string foldoutName = displayName.Split('(', ')')[1];
  66. string foldoutItemCount = displayName.Split('{', '}')[1];
  67. foldoutRemainingItems = Convert.ToInt32(foldoutItemCount);
  68. FoldoutStates.TryAdd(property.name, false);
  69. EditorGUILayout.Space();
  70. FoldoutStates[property.name] =
  71. EditorGUILayout.Foldout(FoldoutStates[property.name], foldoutName, true, _foldoutStyle);
  72. latestFoldoutState = FoldoutStates[property.name];
  73. }
  74. if (foldoutRemainingItems > 0) {
  75. skipProperty = skipProperty || !latestFoldoutState;
  76. EditorGUI.indentLevel += 1;
  77. --foldoutRemainingItems;
  78. }
  79. }
  80. bool hideInInspector = (property.flags & MaterialProperty.PropFlags.HideInInspector) != 0;
  81. if (!skipProperty && !hideInInspector) {
  82. DrawStandard(materialEditor, property);
  83. }
  84. if (targetMaterial.IsKeywordEnabled("_COLORMODE_GRADIENT_TEXTURE") &&
  85. property.type == MaterialProperty.PropType.Texture &&
  86. property.displayName.StartsWith("[_COLORMODE_GRADIENT_TEXTURE]") &&
  87. property.textureValue != null) {
  88. GUILayout.Space(-50);
  89. using (new EditorGUILayout.HorizontalScope()) {
  90. GUILayout.Space(15);
  91. if (GUILayout.Button("Reset", EditorStyles.miniButtonLeft,
  92. GUILayout.Width(60f), GUILayout.ExpandWidth(false))) {
  93. property.textureValue = null;
  94. }
  95. GUILayout.FlexibleSpace();
  96. }
  97. EditorGUILayout.Space(60);
  98. }
  99. EditorGUI.indentLevel = originalIntentLevel;
  100. }
  101. EditorGUILayout.Space();
  102. FoldoutStates[RenderingOptionsName] =
  103. EditorGUILayout.Foldout(FoldoutStates[RenderingOptionsName], RenderingOptionsName, true, _foldoutStyle);
  104. if (FoldoutStates[RenderingOptionsName]) {
  105. EditorGUI.indentLevel += 1;
  106. DrawOpaqueField(targetMaterial);
  107. DrawQueueOffsetField(properties, targetMaterial);
  108. }
  109. }
  110. private void DrawOpaqueField(Material material) {
  111. var opaque = EditorGUILayout.Toggle("Opaque", material.GetTag("RenderType", false) == "Opaque");
  112. if (opaque) {
  113. material.SetOverrideTag("RenderType", "Opaque");
  114. material.SetInt("_ZWrite", 1);
  115. material.renderQueue = (int)RenderQueue.Geometry;
  116. } else {
  117. material.SetOverrideTag("RenderType", "Transparent");
  118. material.SetInt("_ZWrite", 0);
  119. material.renderQueue = (int)RenderQueue.Transparent;
  120. }
  121. }
  122. private void DrawQueueOffsetField(MaterialProperty[] properties, Material material) {
  123. GUIContent queueSlider = new GUIContent("Priority",
  124. "Determines the chronological rendering order for a Material. High values are rendered first.");
  125. const int queueOffsetRange = 50;
  126. MaterialProperty queueOffsetProp = FindProperty("_QueueOffset", properties, false);
  127. if (queueOffsetProp == null) return;
  128. EditorGUI.BeginChangeCheck();
  129. EditorGUI.showMixedValue = queueOffsetProp.hasMixedValue;
  130. var queue = EditorGUILayout.IntSlider(queueSlider, (int)queueOffsetProp.floatValue, -queueOffsetRange,
  131. queueOffsetRange);
  132. if (EditorGUI.EndChangeCheck())
  133. queueOffsetProp.floatValue = queue;
  134. EditorGUI.showMixedValue = false;
  135. material.renderQueue += queue;
  136. }
  137. private void DrawStandard(MaterialEditor materialEditor, MaterialProperty property) {
  138. string displayName = property.displayName;
  139. // Remove everything in brackets.
  140. displayName = Regex.Replace(displayName, @" ?\[.*?\]", string.Empty);
  141. Tooltips.map.TryGetValue(displayName.Trim(), out string tooltip);
  142. displayName = Regex.Replace(displayName, @" ?\{.*?\}", string.Empty);
  143. var guiContent = new GUIContent(displayName, tooltip);
  144. if (property.type == MaterialProperty.PropType.Texture) {
  145. materialEditor.TexturePropertySingleLine(guiContent, property);
  146. } else {
  147. materialEditor.ShaderProperty(property, guiContent);
  148. }
  149. }
  150. private bool ShowColorGradientExportBox(MaterialEditor materialEditor, MaterialProperty property) {
  151. bool isGradientTexture = property.type == MaterialProperty.PropType.Texture &&
  152. property.displayName.StartsWith("[_COLORMODE_GRADIENT_TEXTURE]");
  153. if (isGradientTexture) {
  154. if (property.textureValue != null) {
  155. return false;
  156. }
  157. } else {
  158. return false;
  159. }
  160. var messageContent =
  161. EditorGUIUtility.TrTextContent(
  162. "Before the gradient can be used it needs to be exported as a texture.");
  163. var buttonContent = EditorGUIUtility.TrTextContent("Export");
  164. bool buttonPressed = GradientBoxWithButton(messageContent, buttonContent);
  165. if (buttonPressed) {
  166. var texture = GradientToTexture(_gradient);
  167. PromptTextureSave(materialEditor, texture, property.name);
  168. }
  169. return true;
  170. }
  171. private bool GradientBoxWithButton(GUIContent messageContent, GUIContent buttonContent) {
  172. float boxHeight = 40f;
  173. EditorGUILayout.Space(5);
  174. Rect rect = GUILayoutUtility.GetRect(messageContent, EditorStyles.helpBox);
  175. GUILayoutUtility.GetRect(0f, boxHeight);
  176. rect.height += boxHeight;
  177. var style = new GUIStyle(EditorStyles.helpBox);
  178. style.fontSize += 2;
  179. GUI.Label(rect, messageContent, style);
  180. float secondLineHeight = 20f;
  181. float secondLineY = rect.yMax - secondLineHeight - 15f;
  182. var buttonPosition = new Rect(rect.xMax - 60f - 4f, secondLineY, 60f, secondLineHeight);
  183. bool result = GUI.Button(buttonPosition, buttonContent);
  184. var gradientPosition = new Rect(rect.xMin + 8f, secondLineY, rect.width - 60f - 18f, secondLineHeight);
  185. if (_gradient == null) {
  186. _gradient = new Gradient();
  187. }
  188. _gradient = EditorGUI.GradientField(gradientPosition, _gradient);
  189. EditorGUILayout.Space(10);
  190. return result;
  191. }
  192. private Texture2D GradientToTexture(Gradient g) {
  193. const int width = 256;
  194. Texture2D texture = new Texture2D(width, 1, TextureFormat.RGBA32, /*mipChain=*/false) {
  195. name = "Flat Kit Water Color Gradient",
  196. wrapMode = TextureWrapMode.Clamp,
  197. hideFlags = HideFlags.HideAndDontSave,
  198. filterMode = FilterMode.Point
  199. };
  200. for (float x = 0;
  201. x < width;
  202. x++) {
  203. Color32 color = g.Evaluate(x / (width - 1));
  204. texture.SetPixel(Mathf.CeilToInt(x), 0, color);
  205. }
  206. texture.Apply();
  207. return texture;
  208. }
  209. private void PromptTextureSave(MaterialEditor materialEditor, Texture2D texture, string propertyName) {
  210. Material material = materialEditor.target as Material;
  211. if (material == null) {
  212. return;
  213. }
  214. var pngNameWithExtension = $"{materialEditor.target.name}{propertyName}.png";
  215. var fullPath =
  216. EditorUtility.SaveFilePanel("Save Gradient Texture", "Assets", pngNameWithExtension, "png");
  217. if (fullPath.Length > 0) {
  218. SaveTextureAsPng(texture, fullPath, FilterMode.Point);
  219. var loadedTexture = LoadTexture(fullPath);
  220. if (loadedTexture != null) {
  221. material.SetTexture(propertyName, loadedTexture);
  222. } else {
  223. Debug.LogWarning($"Could not load the texture from {fullPath}");
  224. }
  225. }
  226. }
  227. private void SaveTextureAsPng(Texture2D texture, string fullPath, FilterMode filterMode) {
  228. byte[] bytes = texture.EncodeToPNG();
  229. if (bytes == null) {
  230. Debug.LogError("Could not encode texture as PNG.");
  231. return;
  232. }
  233. File.WriteAllBytes(fullPath, bytes);
  234. AssetDatabase.Refresh();
  235. Debug.Log($"Texture saved as: {fullPath}");
  236. string pathRelativeToAssets = ConvertFullPathToAssetPath(fullPath);
  237. if (pathRelativeToAssets.Length == 0) {
  238. Debug.LogWarning($"Could not save the texture to {fullPath}.");
  239. }
  240. TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(pathRelativeToAssets);
  241. Debug.Assert(importer != null,
  242. $"[FlatKit] Could not create importer at {pathRelativeToAssets}.");
  243. if (importer != null) {
  244. importer.filterMode = filterMode;
  245. importer.textureType = TextureImporterType.Default;
  246. importer.textureCompression = TextureImporterCompression.Uncompressed;
  247. importer.mipmapEnabled = false;
  248. var textureSettings = new TextureImporterPlatformSettings {
  249. format = TextureImporterFormat.RGBA32
  250. };
  251. importer.SetPlatformTextureSettings(textureSettings);
  252. EditorUtility.SetDirty(importer);
  253. importer.SaveAndReimport();
  254. }
  255. Debug.Assert(importer != null,
  256. $"[FlatKit] Could not change import settings of {fullPath} [{pathRelativeToAssets}]");
  257. }
  258. private static Texture2D LoadTexture(string fullPath) {
  259. string pathRelativeToAssets = ConvertFullPathToAssetPath(fullPath);
  260. if (pathRelativeToAssets.Length == 0) {
  261. return null;
  262. }
  263. var loadedTexture = AssetDatabase.LoadAssetAtPath(pathRelativeToAssets, typeof(Texture2D)) as Texture2D;
  264. if (loadedTexture == null) {
  265. Debug.LogError($"[FlatKit] Could not load texture from {fullPath} [{pathRelativeToAssets}].");
  266. return null;
  267. }
  268. loadedTexture.filterMode = FilterMode.Point;
  269. loadedTexture.wrapMode = TextureWrapMode.Clamp;
  270. return loadedTexture;
  271. }
  272. private static string ConvertFullPathToAssetPath(string fullPath) {
  273. int count = (Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar).Length;
  274. return fullPath.Remove(0, count);
  275. }
  276. }